package com.easy.carl.algorithm.String;

import java.util.Arrays;

/**
 * @ClassName StrStr28
 * @Description 实现 strStr() 函数。
 * @Author zheng
 * @Date 2021/12/27 15:48
 * @Version 1.0
 **/
public class StrStr28 {

    public int[] getNext(String needle) {
        int[] next = new int[needle.length()];
        int j = 0;
        next[0] = j;
        for (int i = 1; i < needle.length(); i++) {
            while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            if (needle.charAt(i) == needle.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }

    public int strStr(String haystack, String needle) {
        if (needle.length()==0){
            return 0;
        }
        int[] next = getNext(needle);
        int j = 0;
        for (int i = 0; i < haystack.length(); i++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            if (haystack.charAt(i) == needle.charAt(j)) {
                j++;
            }
            if (j == needle.length()) {
                return i - needle.length() + 1;
            }
        }
        return -1;
    }

    public int strStr1(String haystack, String needle) {
        if (needle.length() == 0) {
            return 0;
        }
        if (haystack.length() < needle.length()) {
            return -1;
        }
        for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
            int tmp = i;
            for (int j = 0; j < needle.length(); j++) {
                if (haystack.charAt(tmp) == needle.charAt(j)) {
                    tmp++;
                } else {
                    break;
                }
                if (j == needle.length() - 1) {
                    return i;
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        StrStr28 strStr28 = new StrStr28();
        //System.out.println(Arrays.toString(strStr28.getNext("aabaaf")));
        System.out.println(strStr28.strStr("aaaaa", "bba"));
    }
}
